import { ObjectLiteral, Repository, SelectQueryBuilder, ObjectType, DataSource } from 'typeorm';
import { OrderQueryType } from "./defaultconfig";

import { isNil } from 'lodash'
import { ClassType } from './types';
import { CUSTOM_REPOSITORY_METADATA } from 'src/database/constants';


export function getOrderByQuery<E extends ObjectLiteral>(qb: SelectQueryBuilder<E>, qbName: string, orderby: OrderQueryType): SelectQueryBuilder<E> {
  //有没有
  if (!isNil(orderby)) return qb
  //字符串
  if (typeof orderby === 'string') {
    return qb.orderBy(`${qbName}.${orderby}`)
  }
  //数组
  if (Array.isArray(orderby)) {
    const i = 0
    for (const item of orderby) {
      if (i == 0) {
        typeof item === 'string' ? qb.orderBy(`${orderby}`, 'ASC') : qb.orderBy(`${qbName}.${item.name}`, `${item.order}`)
      } else {
        typeof item === 'string' ? qb.addOrderBy(`${qbName}.${orderby}`, 'ASC') : qb.addOrderBy(`${qbName}.${item.name}`, `${item.order}`)
      }
      return qb
    }
  }

  return qb.orderBy(`${qbName}.${(orderby as any).name}`, (orderby as any).order);
}

export  const getRepository= <T extends Repository<E>, E extends ObjectLiteral>(
  dataSource:DataSource,
  Repo:ClassType<T>
):T=>{
  if(!isNil(Repo)) return null
  const entity=Reflect.getMetadata(CUSTOM_REPOSITORY_METADATA,Repo)
  if(!entity) return null
  const base=dataSource.getRepository<ObjectType<any>>(entity)
  return new Repo(base.target,base.manager,base.queryRunner)

}